package com.unytech.watersoil.action.security;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.springframework.stereotype.Controller;

import com.unytech.watersoil.action.BaseAction;
import com.unytech.watersoil.common.GlobalEnum;
import com.unytech.watersoil.common.Globals;
import com.unytech.watersoil.entity.security.Permission;
import com.unytech.watersoil.entity.security.User;
import com.unytech.watersoil.service.security.UserService;
import com.unytech.watersoil.service.security.impl.UserServiceImpl;
import com.unytech.watersoil.utils.PermissionUtil;

@Controller("/security")
public class LoginAction extends BaseAction{
	private String username;    //记录用户名
	private String password;    //记录密码，不需回显，无get方法
	private String verifycode;  //记录验证码，不需回显，无get方法
		
	//@Resource(name="UserServiceImpl") UserService userService;  
	UserService userService = new UserServiceImpl();

	public String userLogin()
	{	//超级管理员的名字准备设为"king power"	
		String verifycodeinsession = (String) getSession().get(GlobalEnum.LOGINVERIFYCODE.toString());
		if (verifycodeinsession == null || verifycodeinsession.trim().equals("") || !verifycodeinsession.equals(this.verifycode))
		{	
			getSession().remove(GlobalEnum.LOGINVERIFYCODE.toString());  //判断验证码是否一致之后清除验证码
			setMessage("验证码错误！");			
			return "message";
		}			
		if (this.username == null || this.username.trim().equals("") || this.password == null || this.password.trim().equals(""))
		{	
			setMessage("用户名或密码不能为空！");
			return "message";
		}
			
		User user = userService.loginVerify(this.username, this.password);
		
		if (user == null)
		{
			setMessage("用户名或密码错误！");
			return "message";
		}
		
		if (user.getState() == 0)
		{
			setMessage("此账户已被冻结，请联系管理员！");
			return "message";
		}
		
		//设置用户登录信息
		user.setLoginip(getRequest().getRemoteAddr());
		user.setLogintime(new Date());
		
		System.out.println("Path:"+getRequest().getRequestURL());
		//System.out.println("Path:"+getRequest().getLocalAddr());
		System.out.println("Path:"+getRequest().getRequestURI());
		//System.out.println("Path:"+getRequest().getServletPath());

		Set<User> onlineusers = (Set<User>) getApplication().get(GlobalEnum.ONLINEUSERS.toString());
		if (onlineusers == null) {  //如果记录在线用户的Set的集合为空，添加这个记录在线用户的集合
			//把当前登录用户写入SESSION
			getSession().put(GlobalEnum.LOGINUSER.toString(), user);
			//在全局变量里面添加一个用户的ID，这里为了节省内存空间所以只保存用户ID，用户名，用户IP

			Set<User> adduser = new HashSet<User>();
			User curuser = new User();
			curuser.setUid(user.getUid());
			curuser.setUsername(user.getUsername());
			curuser.setLoginip(user.getLoginip());
			curuser.setLogintime(user.getLogintime());
			adduser.add(curuser);
			getApplication().put(GlobalEnum.ONLINEUSERS.toString(), adduser);
		}
		else
		{   //存储在线用户的Set集合不为空的时候，要从这个集合中取得每个用户和当亲登录的用户的用户名和登录IP比较，以确定此用户是否已经在异地登录					
			for (Iterator it = onlineusers.iterator(); it.hasNext();)
			{
				User tempuser = (User) it.next();
				if (tempuser.getUsername().equals(user.getUsername()))
				{
					if (!tempuser.getLoginip().equals(user.getLoginip()))
					{
						setMessage("此用户已在其他地方登录，请联系管理员！");
						return "message";
					}
				}
				else
				{
					onlineusers.add(user);
					getApplication().put(GlobalEnum.ONLINEUSERS.toString(), onlineusers);
					break;
				}
			}
		}

		//权限处理
		List<Permission> permlist = null;
		if (this.username.toLowerCase().equals(Globals.KINGNAME.toLowerCase()))
		{
			//得到所有的权限
			PermissionUtil permutil = new PermissionUtil();
			permlist = permutil.getXMLPermission();
		}
		else
		{
			//从数据库中取用户所拥有的权限
			permlist = userService.getUserPermission(user);
		}
		
		//把权限写入session
		getSession().put(GlobalEnum.SESSIONPERMISSION.toString(), permlist);
		
		List<Permission> firstmenulist = new ArrayList<Permission>();
		for (int i=0; i<permlist.size(); i++)
		{
			if (permlist.get(i).getParentId().trim().equals(Globals.ROOTPERMISSIONID))
			{
				firstmenulist.add(permlist.get(i));
			}
		}
		//请求index.jsp的时候默认显示一级菜单，故此处写给前台一个一级菜单的List
		getRequest().setAttribute("firstmenulist", firstmenulist);
	
		return "loginok";	
	}

	
	public String userLogout()
	{
		
		Set<String> onlineusers = (Set<String>) getApplication().get(GlobalEnum.ONLINEUSERS.toString());
		User user = (User) getSession().get(GlobalEnum.LOGINUSER.toString());
		
		if (onlineusers.contains(user))
		{
			onlineusers.remove(user);
			getApplication().put(GlobalEnum.ONLINEUSERS.toString(), onlineusers);
		}
	
		getSession().remove(GlobalEnum.LOGINUSER.toString());
		getSession().remove(GlobalEnum.SESSIONPERMISSION.toString());
		getSession().remove(GlobalEnum.LOGINVERIFYCODE.toString());
		System.out.println("退出系统！");
		return "logoutok";
	}
	
	
	
	
	public String verifyCode()
	{
		try {
	        int width = 40;  //图片宽度    
	        int height = 18;  //图片高度
	        int length = 4; //验证码长度
	        // 取得一个length位随机字母数字字符串
	        Random random = new Random();
	        String sRand="";
	        for (int i=0;i<length;i++){
	        String rand=String.valueOf(random.nextInt(10));
	        sRand += rand;
	        }
			String code = sRand;    
			System.out.println("验证码："+code); 

			//把验证码存入session，注意比较完之后清除session.    
			getSession().put(GlobalEnum.LOGINVERIFYCODE.toString(), code);
			
			
			getResponse().setContentType("images/jpeg");  //设置内容格式  
			getResponse().setHeader("Pragma", "No-cache");  //禁用浏览器缓存    
			getResponse().setHeader("Cache-Control", "no-cache");    
			getResponse().setDateHeader("Expires", 0);    
		     
			ServletOutputStream out = getResponse().getOutputStream();    
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    
			Graphics g = image.getGraphics();   
			// 设定背景色    
			g.setColor(getRandColor(200, 250));    
			g.fillRect(0, 0, width, height);    
		     
			// 设定字体    
			Font mFont = new Font("Times New Roman", Font.BOLD, 18);// 设置字体    
			g.setFont(mFont);    
		     
			// 画边框    
			// g.setColor(Color.BLACK);    
			// g.drawRect(0, 0, width - 1, height - 1);    
		     
			// 随机产生干扰线，使图象中的认证码不易被其它程序探测到    
			g.setColor(getRandColor(160, 200));    
			// 生成随机类   
			for (int ii = 0; ii < 155; ii++) {    
				int x2 = random.nextInt(width);    
				int y2 = random.nextInt(height);    
				int x3 = random.nextInt(12);    
				int y3 = random.nextInt(12);    
				g.drawLine(x2, y2, x2 + x3, y2 + y3);    
			 }    
		     
			// 将认证码显示到图象中    
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));    
		    g.drawString(code, 2, 16);    
		    // 图象生效    
		    g.dispose();    
		    // 输出图象到页面    
		    ImageIO.write((BufferedImage) image, "JPEG", out);    
		    out.close();    
	    } catch (Exception e) {    
	         e.printStackTrace();    
	    }  
	    
	    return null;    
	}    
	
    private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色    
		Random random = new Random();    
		if (fc > 255)    
			fc = 255;    
		if (bc > 255)    
			bc = 255;    
		int r = fc + random.nextInt(bc - fc);    
		int g = fc + random.nextInt(bc - fc);    
		int b = fc + random.nextInt(bc - fc); 
		
		return new Color(r, g, b);    
    } 
    
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setVerifycode(String verifycode) {
		this.verifycode = verifycode;
	}
}
